package Question;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 定义一个方法，查询user表的数据将其封装成对象，然后装在到集合中，返回
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2021-12-14-14:56 14:56
 */
public class DataCollation {
    public static void main(String[] args) {
        List<User> list=new DataCollation().tidy();
        for (User user : list) {
            System.out.println(user);
        }

    }
    /**
     * @Description: 将cartoondb数据库中的user表中的数据进行整理，保存到List集合中
     * @Param: []
     * @return: java.util.List<Question.User>
     * @Author: Mc.Chai
     * @Date: 2021/12/14
     * @Time:
     */
    public List<User> tidy(){
        List<User> userList = new ArrayList<User>();
        ResultSet resultSet=null;
        Statement statement=null;
        Connection connection=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql:///cartoondb", "root", "123456");
            statement = connection.createStatement();
            String sql="select * from user";
            resultSet = statement.executeQuery(sql);
            //创建User对象，每一条记录为一个对象
            User user = null;
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String userpwd = resultSet.getString("userpwd");
                String truename = resultSet.getString("truename");
                int age = resultSet.getInt("age");
                Date regdate = resultSet.getDate("regdate");
                user=new User(id,username,userpwd,truename,age,regdate);
                userList.add(user);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return userList;
    }
}
